<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="剧集标题" prop="title">
              <el-input v-model="queryParams.title" placeholder="请输入剧集标题" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['content:episodes:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['content:episodes:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['content:episodes:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['content:episodes:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="episodesList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="剧集ID" align="center" prop="episodeId" v-if="true" />
        <el-table-column label="短剧ID" align="center" prop="dramaId" />
        <el-table-column label="剧集标题" align="center" prop="title" />
        <el-table-column label="集数" align="center" prop="episodeNumber" />
        <el-table-column label="剧集封面URL" align="center" prop="cover" />
        <el-table-column label="时长(秒)" align="center" prop="duration" />
        <el-table-column label="剧集简介" align="center" prop="description" />
        <el-table-column label="视频URL" align="center" prop="videoUrl" />
        <el-table-column label="高清视频URL" align="center" prop="videoUrlHd" />
        <el-table-column label="标清视频URL" align="center" prop="videoUrlSd" />
        <el-table-column label="字幕文件URL" align="center" prop="subtitleUrl" />
        <el-table-column label="是否免费：0收费，1免费" align="center" prop="isFree" />
        <el-table-column label="是否预告片：0否，1是" align="center" prop="isTrailer" />
        <el-table-column label="金币价格" align="center" prop="coinPrice" />
        <el-table-column label="播放次数" align="center" prop="playCount" />
        <el-table-column label="点赞数" align="center" prop="likeCount" />
        <el-table-column label="评论数" align="center" prop="commentCount" />
        <el-table-column label="分享数" align="center" prop="shareCount" />
        <el-table-column label="弹幕数" align="center" prop="danmakuCount" />
        <el-table-column label="发布时间" align="center" prop="publishTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.publishTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态：0下架，1上架，2审核中" align="center" prop="status" />
        <el-table-column label="审核状态：0待审核，1通过，2拒绝" align="center" prop="auditStatus" />
        <el-table-column label="审核拒绝原因" align="center" prop="auditReason" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['content:episodes:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['content:episodes:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改剧集管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="episodesFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="短剧ID" prop="dramaId">
          <el-input v-model="form.dramaId" placeholder="请输入短剧ID" />
        </el-form-item>
        <el-form-item label="剧集标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入剧集标题" />
        </el-form-item>
        <el-form-item label="集数" prop="episodeNumber">
          <el-input v-model="form.episodeNumber" placeholder="请输入集数" />
        </el-form-item>
        <el-form-item label="剧集封面URL" prop="cover">
          <el-input v-model="form.cover" placeholder="请输入剧集封面URL" />
        </el-form-item>
        <el-form-item label="时长(秒)" prop="duration">
          <el-input v-model="form.duration" placeholder="请输入时长(秒)" />
        </el-form-item>
        <el-form-item label="剧集简介" prop="description">
            <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="视频URL" prop="videoUrl">
          <el-input v-model="form.videoUrl" placeholder="请输入视频URL" />
        </el-form-item>
        <el-form-item label="高清视频URL" prop="videoUrlHd">
          <el-input v-model="form.videoUrlHd" placeholder="请输入高清视频URL" />
        </el-form-item>
        <el-form-item label="标清视频URL" prop="videoUrlSd">
          <el-input v-model="form.videoUrlSd" placeholder="请输入标清视频URL" />
        </el-form-item>
        <el-form-item label="字幕文件URL" prop="subtitleUrl">
          <el-input v-model="form.subtitleUrl" placeholder="请输入字幕文件URL" />
        </el-form-item>
        <el-form-item label="是否免费：0收费，1免费" prop="isFree">
          <el-input v-model="form.isFree" placeholder="请输入是否免费：0收费，1免费" />
        </el-form-item>
        <el-form-item label="是否预告片：0否，1是" prop="isTrailer">
          <el-input v-model="form.isTrailer" placeholder="请输入是否预告片：0否，1是" />
        </el-form-item>
        <el-form-item label="金币价格" prop="coinPrice">
          <el-input v-model="form.coinPrice" placeholder="请输入金币价格" />
        </el-form-item>
        <el-form-item label="播放次数" prop="playCount">
          <el-input v-model="form.playCount" placeholder="请输入播放次数" />
        </el-form-item>
        <el-form-item label="点赞数" prop="likeCount">
          <el-input v-model="form.likeCount" placeholder="请输入点赞数" />
        </el-form-item>
        <el-form-item label="评论数" prop="commentCount">
          <el-input v-model="form.commentCount" placeholder="请输入评论数" />
        </el-form-item>
        <el-form-item label="分享数" prop="shareCount">
          <el-input v-model="form.shareCount" placeholder="请输入分享数" />
        </el-form-item>
        <el-form-item label="弹幕数" prop="danmakuCount">
          <el-input v-model="form.danmakuCount" placeholder="请输入弹幕数" />
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker clearable
            v-model="form.publishTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择发布时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态：0下架，1上架，2审核中" prop="status">
          <el-input v-model="form.status" placeholder="请输入状态：0下架，1上架，2审核中" />
        </el-form-item>
        <el-form-item label="审核状态：0待审核，1通过，2拒绝" prop="auditStatus">
          <el-input v-model="form.auditStatus" placeholder="请输入审核状态：0待审核，1通过，2拒绝" />
        </el-form-item>
        <el-form-item label="审核拒绝原因" prop="auditReason">
          <el-input v-model="form.auditReason" placeholder="请输入审核拒绝原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Episodes" lang="ts">
import { listEpisodes, getEpisodes, delEpisodes, addEpisodes, updateEpisodes } from '@/api/content/episodes';
import { EpisodesVO, EpisodesQuery, EpisodesForm } from '@/api/content/episodes/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const episodesList = ref<EpisodesVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const episodesFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: EpisodesForm = {
  episodeId: undefined,
  dramaId: undefined,
  title: undefined,
  episodeNumber: undefined,
  cover: undefined,
  duration: undefined,
  description: undefined,
  videoUrl: undefined,
  videoUrlHd: undefined,
  videoUrlSd: undefined,
  subtitleUrl: undefined,
  isFree: undefined,
  isTrailer: undefined,
  coinPrice: undefined,
  playCount: undefined,
  likeCount: undefined,
  commentCount: undefined,
  shareCount: undefined,
  danmakuCount: undefined,
  publishTime: undefined,
  status: undefined,
  auditStatus: undefined,
  auditReason: undefined,
}
const data = reactive<PageData<EpisodesForm, EpisodesQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: undefined,
    params: {
    }
  },
  rules: {
    episodeId: [
      { required: true, message: "剧集ID不能为空", trigger: "blur" }
    ],
    dramaId: [
      { required: true, message: "短剧ID不能为空", trigger: "blur" }
    ],
    title: [
      { required: true, message: "剧集标题不能为空", trigger: "blur" }
    ],
    episodeNumber: [
      { required: true, message: "集数不能为空", trigger: "blur" }
    ],
    duration: [
      { required: true, message: "时长(秒)不能为空", trigger: "blur" }
    ],
    videoUrl: [
      { required: true, message: "视频URL不能为空", trigger: "blur" }
    ],
    isFree: [
      { required: true, message: "是否免费：0收费，1免费不能为空", trigger: "blur" }
    ],
    isTrailer: [
      { required: true, message: "是否预告片：0否，1是不能为空", trigger: "blur" }
    ],
    coinPrice: [
      { required: true, message: "金币价格不能为空", trigger: "blur" }
    ],
    playCount: [
      { required: true, message: "播放次数不能为空", trigger: "blur" }
    ],
    likeCount: [
      { required: true, message: "点赞数不能为空", trigger: "blur" }
    ],
    commentCount: [
      { required: true, message: "评论数不能为空", trigger: "blur" }
    ],
    shareCount: [
      { required: true, message: "分享数不能为空", trigger: "blur" }
    ],
    danmakuCount: [
      { required: true, message: "弹幕数不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态：0下架，1上架，2审核中不能为空", trigger: "blur" }
    ],
    auditStatus: [
      { required: true, message: "审核状态：0待审核，1通过，2拒绝不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询剧集管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listEpisodes(queryParams.value);
  episodesList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  episodesFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: EpisodesVO[]) => {
  ids.value = selection.map(item => item.episodeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加剧集管理";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: EpisodesVO) => {
  reset();
  const _episodeId = row?.episodeId || ids.value[0]
  const res = await getEpisodes(_episodeId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改剧集管理";
}

/** 提交按钮 */
const submitForm = () => {
  episodesFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.episodeId) {
        await updateEpisodes(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addEpisodes(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: EpisodesVO) => {
  const _episodeIds = row?.episodeId || ids.value;
  await proxy?.$modal.confirm('是否确认删除剧集管理编号为"' + _episodeIds + '"的数据项？').finally(() => loading.value = false);
  await delEpisodes(_episodeIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('content/episodes/export', {
    ...queryParams.value
  }, `episodes_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
